import {Component, OnInit, Input, AfterViewInit, OnDestroy} from '@angular/core';
import {DomSanitizer} from '@angular/platform-browser';
import {HttpService} from '@kylin/http';

@Component({
    selector: 'kylin-flow-chart',
    templateUrl: './flow-chart.component.html',
    styleUrls: ['./flow-chart.component.css']
})
export class FlowChartComponent implements OnInit, AfterViewInit, OnDestroy {

    @Input() procInsId = '';

    imgData: string;
    interval: any;
    dataSet: any[];

    private processImgPath = '/germplasm/processImg/';
    private processLogPath = '/germplasm/processLog/';
    private img1;
    private img2;
    private imgDataBase = 'data:image/png;base64,';

    constructor(private http: HttpService, private sanitizer: DomSanitizer) {

    }

    private fetchProcessImg() {
        this.http.get(this.processImgPath + this.procInsId)
            .then(res => {
                if (res.result) {
                    this.switchImgInit(res.result);
                }
            })
            .catch(err => {
                console.warn(err);
            });
    }

    private fetchProcessLog() {
        this.http.get(this.processLogPath + this.procInsId)
            .then(res => {
                if (res.result) {
                    this.dataSet = res.result;
                }
            })
            .catch(err => {
                console.warn(err);
            });
    }

    ngOnInit() {
        this.fetchProcessImg();
        this.fetchProcessLog();
    }


    ngAfterViewInit() {

    }

    private switchImgInit(data: Array<string>) {
        if (data) {
            this.img1 = this.getSafeUrl(this.imgDataBase + data[0]);
            this.img2 = this.getSafeUrl(this.imgDataBase + data[1]);
            this.imgData = this.img1;
            this.interval = setInterval(() => {
                this.imgData === this.img1 ? this.imgData = this.img2 : this.imgData = this.img1;
            }, 500);
        }
    }

    private getSafeUrl(url: string) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }

    ngOnDestroy() {
        if (this.interval) {
            clearInterval(this.interval);
        }
    }
}
